package com.htthorizon.model.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.IPage;
import com.github.pagehelper.Page;
import com.google.common.collect.Ordering;
import com.htthorizon.common.core.context.SecurityContextHolder;
import com.htthorizon.common.core.exception.ServiceException;
import com.htthorizon.common.core.utils.IDUtils;
import com.htthorizon.common.core.utils.StringUtils;
import com.htthorizon.common.core.web.page.TableDataInfo;
import com.htthorizon.model.domain.ModelInfo;
import com.htthorizon.model.domain.ModelMessage;
import com.htthorizon.model.domain.ModelMessageFlow;
import com.htthorizon.model.domain.ModelMessageNextUser;
import com.htthorizon.model.enums.MessageStatus;
import com.htthorizon.model.mapper.ModelMessageMapper;
import com.htthorizon.model.mapper.ModelMessageNextUserMapper;
import com.htthorizon.model.request.ModelMessageAddReq;
import com.htthorizon.model.request.ModelMessageForward;
import com.htthorizon.model.request.ModelMessageReply;
import com.htthorizon.model.request.ModelMessageSearchReq;
import com.htthorizon.model.response.ModelMessageVo;
import com.htthorizon.system.api.RemoteUserService;
import com.htthorizon.system.api.domain.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Brilliant
 */
@Service
@Slf4j
public class ModelMessageServiceImpl implements IModelMessageService{

    @Autowired
    private IModelMessageFlowService modelMessageFlowService;

    @Autowired
    private ModelMessageMapper modelMessageMapper;

    @Autowired
    private ModelMessageNextUserMapper modelMessageNextUserMapper;

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private IModelInfoService modelInfoService;

    @Override
    public boolean addMessage(ModelMessageAddReq search) {
        log.debug("创建消息...");
        Long loginUserId = SecurityContextHolder.getUserId();
        String loginUserName = SecurityContextHolder.getUserName();
        DateTime now = DateUtil.date();
        // 前端不再传模型名称 12/20
//        if (!StringUtils.isEmpty(search.getModelName())) {
//            ModelInfo modelInfo = modelInfoService.selectModelInfoById(search.getModelId());
//            search.setModelName(modelInfo.getModelName());
//        }

        ModelMessage modelMessage = new ModelMessage();
        BeanUtils.copyProperties(search,modelMessage);

        String messageID = IDUtils.generateId();
        modelMessage.setMessageId(messageID);
        modelMessage.setQuestionStatus(MessageStatus.CEEKING.getValue());
        modelMessage.setCreateBy(loginUserName);
        modelMessage.setCreateId(loginUserId);
        modelMessage.setCreateTime(now);

        Long sum = modelMessageMapper.insert(modelMessage);

        ModelMessageFlow modelMessageFlow = new ModelMessageFlow();
        modelMessageFlow.setModelMessageId(modelMessage.getId());
        modelMessageFlow.setModelMessageStatus(MessageStatus.CEEKING.getValue());
        modelMessageFlow.setStatus("创建消息");
        modelMessageFlow.setCreateBy(loginUserName);
        modelMessageFlow.setCreateId(loginUserId);
        modelMessageFlow.setCreateTime(now);
        Long flowId = modelMessageFlowService.addFlow(modelMessageFlow);


        Long sysUserId = search.getSysUserId();
        String sysUserName = search.getSysUserName();
        ModelMessageNextUser modelMessageNextUser = new ModelMessageNextUser();
        if (StringUtils.isEmpty(sysUserName)){
         SysUser sysUser= remoteUserService.getUserById(sysUserId);
            modelMessageNextUser.setSysUserName(sysUser.getUserName());
        }else {
            modelMessageNextUser.setSysUserName(sysUserName);
        }
        // todo 组织机构完善后查询
//        remoteUserService.getUserInfo()

        modelMessageNextUser.setSysUserId(sysUserId);

        modelMessageNextUser.setModelMessageId(modelMessage.getId());
        modelMessageNextUser.setModelMessageFlowId(flowId);
        modelMessageNextUserMapper.insert(modelMessageNextUser);
        return true;
    }

    @Override
    public ModelMessageVo getById(Long id) {
        ModelMessageVo modelMessageVo = new ModelMessageVo();
        ModelMessage modelMessage=  modelMessageMapper.findById(id);
        BeanUtils.copyProperties(modelMessage,modelMessageVo);
        // todo 封装流程 以及下一步人
        return modelMessageVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean reply(ModelMessageReply modelMessageReply) {
        Long userId = SecurityContextHolder.getUserId();
        String userName = SecurityContextHolder.getUserName();
        DateTime now = DateTime.now();

        ModelMessage modelMessage = new ModelMessage();
        modelMessage.setId(modelMessageReply.getId());
        modelMessage.setQuestionStatus(MessageStatus.REPLED.getValue());
        modelMessage.setUpdateBy(userName);
        modelMessage.setUpdateId(userId);
        modelMessage.setUpdateTime(now);
        modelMessage.setFileUrl2(modelMessageReply.getFileUrl2());
        modelMessageMapper.updateByID(modelMessage);

        ModelMessageFlow modelMessageFlow = new ModelMessageFlow();
        modelMessageFlow.setCreateTime(now);
        modelMessageFlow.setCreateId(userId);
        modelMessageFlow.setCreateBy(userName);
        modelMessageFlow.setStatus("已回复");
        modelMessageFlow.setFileUrl(modelMessageReply.getFileUrl());
        modelMessageFlow.setModelMessageId(modelMessageReply.getId());
        modelMessageFlow.setReplyMessage(modelMessageReply.getReplyMessage());
        modelMessageFlow.setModelMessageStatus(MessageStatus.REPLED.getValue());
        modelMessageFlowService.addFlow(modelMessageFlow);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean nextUser(ModelMessageForward modelMessageForward) {
        Long userId = SecurityContextHolder.getUserId();
        // todo 转办获取用户ID
        System.err.println("转办获取用户ID"+userId);
        ModelMessage modelMessage1 = modelMessageMapper.selectByPrimaryKey(modelMessageForward.getId());
        if (MessageStatus.REPLED.getValue().equals(modelMessage1.getQuestionStatus())) {
            throw new ServiceException("消息已回复");
        }
        String userName = SecurityContextHolder.getUserName();
        DateTime now = DateTime.now();

        ModelMessage modelMessage = new ModelMessage();
        modelMessage.setId(modelMessageForward.getId());
        modelMessage.setQuestionStatus(MessageStatus.REPLING.getValue());
        modelMessage.setUpdateBy(userName);
        modelMessage.setUpdateId(userId);
        modelMessage.setUpdateTime(now);
        int i=  modelMessageMapper.updateByID(modelMessage);

        ModelMessageFlow modelMessageFlow = new ModelMessageFlow();
        modelMessageFlow.setModelMessageId(modelMessageForward.getId());
        modelMessageFlow.setCreateTime(now);
        modelMessageFlow.setCreateId(userId);
        modelMessageFlow.setCreateBy(userName);
        modelMessageFlow.setStatus("已转办");
        modelMessageFlow.setModelMessageStatus(MessageStatus.REPLING.getValue());
        modelMessageFlow.setForwardText(modelMessageForward.getForwardText());
        modelMessageFlow.setNextUser(modelMessageForward.getSysUserName());
        modelMessageFlow.setNextUserId(modelMessageForward.getId());
        Long l = modelMessageFlowService.addFlow(modelMessageFlow);

        ModelMessageNextUser modelMessageNextUser = new ModelMessageNextUser();
        modelMessageNextUser.setSysUserName(modelMessageForward.getSysUserName());
        modelMessageNextUser.setSysUserId(modelMessageForward.getSysUserId());
        modelMessageNextUser.setModelMessageId(modelMessageForward.getId());
        modelMessageNextUser.setModelMessageFlowId(modelMessageFlow.getId());
        modelMessageNextUserMapper.insert(modelMessageNextUser);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean del(Long id) {
      ModelMessage modelMessage=  modelMessageMapper.getById(id);
        if (modelMessage.getQuestionStatus().equals(MessageStatus.REPLED.getValue())){
            throw new ServiceException("已回复消息,不能撤销");
        }
        modelMessageMapper.delByID(id);
        modelMessageFlowService.delByMessageId(id);
        modelMessageNextUserMapper.delByMessageId(id);
        return true;
    }

    @Override
    public TableDataInfo getPage(Page<ModelMessageVo> pages, ModelMessageSearchReq search,TableDataInfo tableDataInfo) {
        List<ModelMessageVo> list=new ArrayList<>();
        if (search.getType()==2){
            int count = modelMessageMapper.count(search);
            tableDataInfo.setTotal(count);
            List<ModelMessage> modelMessages=  modelMessageMapper.getPages((pages.getPageNum()-1)*pages.getPageSize(),pages.getPageSize(),search);
             modelMessages.forEach(modelMessage -> {
                 ModelMessageVo modelMessageVo = new ModelMessageVo();
                 BeanUtils.copyProperties(modelMessage,modelMessageVo);
                 List<ModelMessageFlow> flows=   modelMessageFlowService.getByMessageId(modelMessageVo.getId());
                 modelMessageVo.setFlows(flows);
                 list.add(modelMessageVo);
             });
        }else {
            List<Long> list1=new ArrayList<>();
            Long userId = SecurityContextHolder.getUserId();
            List<Long> ids= modelMessageFlowService.getModelMessageIdByUserId(userId);
            List<Long> ids2= modelMessageNextUserMapper.getNextModelMessageByUserId(userId);
            Set<Long> set=new HashSet<>();
            set.addAll(ids);
            set.addAll(ids2);
            list1.addAll(set);

            tableDataInfo.setTotal(list1.size());

            List<ModelMessage> list2=   modelMessageMapper.getMy((pages.getPageNum()-1)*pages.getPageSize(),pages.getPageSize(),list1,search);
            list2.forEach(modelMessage -> {
                ModelMessageVo modelMessageVo = new ModelMessageVo();
                BeanUtils.copyProperties(modelMessage,modelMessageVo);
                List<ModelMessageFlow> flows=   modelMessageFlowService.getByMessageId(modelMessageVo.getId());
                modelMessageVo.setFlows(flows);
                list.add(modelMessageVo);
            });

        }
        tableDataInfo.setRows(list);
        return tableDataInfo;
    }

    @Override
    public List<ModelMessage> queryTimeLimit(DateTime date, DateTime lastMonth) {
        return modelMessageMapper.selectByTimeLimit(date,lastMonth);
    }
}
